package graphics;

import Intelligence.AIPlayer;
import controller.DefaultController;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import model.Checker;
import model.Player;
import util.Difficulty;
import util.Movement;
import util.Position;

/**
 *
 * @author José Ignacio Rivero Dávila
 */
public class AdvancedView extends AbstractViewPanel implements ActionListener {

    private BoardDisplay damas;
    public static boolean humanColor = Player.BLACK;
    private Movement move;
    private DefaultController control;
    private Position selected;

    /**
     * Creates new form AdvancedView
     */
    public AdvancedView(DefaultController control) {
        move = new Movement();
        this.control = control;

        initComponents();
        damas = new BoardDisplay(400, Player.BLACK);
        jPanel2.add(damas);
        damas.setView(this);
        damas.init();

        displayDifficulty(control.getCurrentDifficulty());
        displayDifficultyCB(control.getCurrentDifficulty());
        
        doMoveButton.setEnabled(true);
        clearMoveButton.setEnabled(true);
        computerMoveButton.setEnabled(false);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        movesTextArea = new javax.swing.JTextArea();
        doMoveButton = new javax.swing.JButton();
        clearMoveButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        heuristicLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        whoseTurnLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        difficultyLabel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lastMoveTextLabel = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        timeLabel = new javax.swing.JLabel();
        computerMoveButton = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        difficultyComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );

        jPanel1.setEnabled(false);

        movesTextArea.setColumns(20);
        movesTextArea.setRows(5);
        jScrollPane1.setViewportView(movesTextArea);

        doMoveButton.setText("Do move");
        doMoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doMoveButtonActionPerformed(evt);
            }
        });

        clearMoveButton.setText("Clear Move");
        clearMoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearMoveButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(doMoveButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(clearMoveButton)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(clearMoveButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(doMoveButton)
                .addContainerGap())
        );

        jLabel2.setText("Heuristic:");

        heuristicLabel.setText("0");

        jLabel3.setText("Whose turn:");

        whoseTurnLabel.setText("black");

        jLabel4.setText("Difficulty: ");

        difficultyLabel.setText("-");

        jLabel6.setText("Last move: ");

        lastMoveTextLabel.setText("-");

        jLabel1.setText("Time computer thought (ms): ");

        timeLabel.setText("-");

        computerMoveButton.setText("Computer Move");
        computerMoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                computerMoveButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jLabel2)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(heuristicLabel))
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jLabel3)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(whoseTurnLabel))
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jLabel4)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(difficultyLabel))
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jLabel6)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(lastMoveTextLabel))
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jLabel1)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(timeLabel)))
                        .add(0, 72, Short.MAX_VALUE))
                    .add(computerMoveButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(heuristicLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(whoseTurnLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(difficultyLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(lastMoveTextLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(timeLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(computerMoveButton)
                .addContainerGap(45, Short.MAX_VALUE))
        );

        difficultyComboBox.setModel(new DefaultComboBoxModel(Difficulty.values()));
        difficultyComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                difficultyComboBoxActionPerformed(evt);
            }
        });

        jLabel5.setText("Set Difficulty:");

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
                .add(15, 15, 15)
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 83, Short.MAX_VALUE)
                .add(difficultyComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(44, 44, 44))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(difficultyComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel5)))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(50, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void doMoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doMoveButtonActionPerformed
        // TODO add your handling code here:
        try {
            control.humanMoves(move);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage() + "\nSe borrará el movimiento");
            move = new Movement();
            movesTextArea.setText("");
            damas.clearHighlight();
            return;
        }
        clearMove();
        doMoveButton.setEnabled(false);
        clearMoveButton.setEnabled(false);
        computerMoveButton.setEnabled(true);

    }//GEN-LAST:event_doMoveButtonActionPerformed

    private void difficultyComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_difficultyComboBoxActionPerformed
        // TODO add your handling code here:
        int difficultyChosen = difficultyComboBox.getSelectedIndex();
        control.setDifficulty(Difficulty.values()[difficultyChosen]);
    }//GEN-LAST:event_difficultyComboBoxActionPerformed

    private void clearMoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearMoveButtonActionPerformed
        // TODO add your handling code here:
        clearMove();

    }//GEN-LAST:event_clearMoveButtonActionPerformed

    private void computerMoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_computerMoveButtonActionPerformed
        // TODO add your handling code here:
        long currentTime = System.currentTimeMillis();

        try {
            control.aiMove();
            long timeAfterMethod = System.currentTimeMillis();
            timeLabel.setText((timeAfterMethod - currentTime) + "");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage());
            return;
        }
        doMoveButton.setEnabled(true);
        clearMoveButton.setEnabled(true);
        computerMoveButton.setEnabled(false);
    }//GEN-LAST:event_computerMoveButtonActionPerformed

    private void clearMove() {
        move = new Movement();
        movesTextArea.setText("");
        damas.clearHighlight();
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearMoveButton;
    private javax.swing.JButton computerMoveButton;
    private javax.swing.JComboBox difficultyComboBox;
    private javax.swing.JLabel difficultyLabel;
    private javax.swing.JButton doMoveButton;
    private javax.swing.JLabel heuristicLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lastMoveTextLabel;
    private javax.swing.JTextArea movesTextArea;
    private javax.swing.JLabel timeLabel;
    private javax.swing.JLabel whoseTurnLabel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {

        if (evt.getPropertyName().equals("lastMovement")) {
            movement((Movement) evt.getNewValue());
        } else if (evt.getPropertyName().equals("whoseTurn")) {
            changeTurn((Boolean) evt.getNewValue());
        } else if (evt.getPropertyName().equals("lastAlphaBetaValue")) {
            displayHeuristic((Integer) evt.getNewValue());
        } else if (evt.getPropertyName().equals("lastEaten")) {
            eat((Position) evt.getNewValue());
        } else if (evt.getPropertyName().equals("difficulty")) {
            displayDifficulty((Difficulty) evt.getNewValue());
        } else if (evt.getPropertyName().equals("lastMove")) {
            displayLastMove((Movement) evt.getNewValue());
        } else if (evt.getPropertyName().equals("positions")) {
            checkPositions((Checker[][]) evt.getNewValue());
        } else if (evt.getPropertyName().equals("gameWonByPlayer")) {
            gameWon((Checker) evt.getNewValue());

        }

        /*
         *
         * positions lastMovement whoseTurn lastAlphaBetaValue lastEaten
         */
    }

    private void movement(Movement movement) {
        damas.move(movement);
    }

    private void displayDifficulty(Difficulty difficulty) {
        difficultyLabel.setText(difficulty.toString());
    }

    private void displayDifficultyCB(Difficulty difficulty) {
        difficultyComboBox.setSelectedItem(difficulty);
    }

    private void changeTurn(Boolean whoseTurn) {
        if (whoseTurn.booleanValue() == AdvancedView.humanColor) {

            doMoveButton.setEnabled(true);
            move = new Movement();
            whoseTurnLabel.setText("Human");
            movesTextArea.setText("");
        } else {
            whoseTurnLabel.setText("Computer");
        }


    }

    private void displayHeuristic(Integer integer) {
        heuristicLabel.setText(integer.toString());
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    private void eat(Position position) {
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    public void checkPositions(Checker[][] positions) throws RuntimeException {
        //damas.setBoard(positions);
        //damas.redraw();
        //check that my board is equal to the board passed, else throw exception
    }

    private void displayLastMove(Movement movement) {
        lastMoveTextLabel.setText(movement.toString());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void selectedPosition(Position pos) {
        move.addPosition(pos);
        if (move.getListOfPositions().size() > 1) {
            if (Math.abs(move.getListOfPositions().get(0).i - move.getListOfPositions().get(1).i) >= 2
                    || Math.abs(move.getListOfPositions().get(0).j - move.getListOfPositions().get(1).j) >= 2) {
                move.setIsJump(true);
            }
        }
        movesTextArea.setText(move.toString());

    }

    private void gameWon(Checker c) {
        if (Checker.BLACK == c) {
            JOptionPane.showMessageDialog(rootPane, "¡El jugador NEGRO ha ganado!");
        } else {
            JOptionPane.showMessageDialog(rootPane, "¡El jugador ROJO ha ganado!");
        }
    }
}
